package com.example.livereplay.common.service.imp;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.livereplay.common.model.enity.Comment;
import com.example.livereplay.common.service.CommentService;
import com.example.livereplay.exception.BusinessException;
import com.example.livereplay.common.mapper.CommentMapper;
import com.example.livereplay.common.model.request.InsertCommentRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    //违禁词
    private static final Set<String> prohibitedWords = new HashSet<>();
    static {
        prohibitedWords.add("");
    }

    //输入弹幕
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean insert(InsertCommentRequest insertCommentRequest){
        String commentContent = insertCommentRequest.getComment();
        for (String prohibitedWord : prohibitedWords){
            Pattern pattern =Pattern.compile(prohibitedWord,Pattern.CASE_INSENSITIVE);
            Matcher matcher=pattern.matcher(commentContent);
            if(matcher.find()){
                throw new BusinessException("触犯违禁词，警告...");
            }
        }
        Comment comment=new Comment();
        BeanUtil.copyProperties(insertCommentRequest,comment);
        return save(comment);
    }

    //输出弹幕
    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<Comment> findByVideoId(String id){
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<Comment>()
                .eq(Comment::getAttachmentId, id)
                .orderByAsc(Comment::getTime);

        List<Comment> commentList = list(queryWrapper);
        if (CollectionUtils.isEmpty(commentList)) {
            return Collections.emptyList();
        }
        return commentList;
    }
}
